/**
 * Created by lx on 2017/9/15.
 */
angular.module('module.charge')
    .controller('ChargeMainController', ChargeMainController);
ChargeMainController.$inject = ['$state', '$scope', '$filter', '$localStorage', 'ChargeService'];
function ChargeMainController($state, $scope, $filter, $localStorage, ChargeService) {

    // 初始化
    var vm = this;
    if (!$localStorage[environmental + "shopid"]) {
        $localStorage.$reset();
        $state.go('login');
    }
    vm.initialization_date = initialization_date;
    vm.initCount = initCount;
    var shopid = $localStorage[environmental + "shopid"];
    var date = new Date();
    var TotalFee = {
        tradeTotalFee: 0
    };
    active(date);
    var myChart = echarts.init(document.getElementById('main'));

    /*师傅版*/
    function active(startTime) {
        TotalFee = {
            tradeTotalFee: 0
        };
        initialization_date(); // 时间控件初始化
        vm.profit = false;
        vm.details = false;
        startTime.setDate(1);
        // 得到不带格式的不带day
        vm.settleDate = dataFilter(startTime, 'yyyyMM');
        // 得到带格式
        vm.time_start = dataFilter(startTime, 'yyyy/MM');
        // 查询当天流水所需日期
        var startT = new Date();
        var judgedate = dataFilter(startT, 'yyyyMM'); // 用于判断
        vm.startT = dataFilter(startT, 'yyyy/MM/dd');
        var intradaydate = parseInt(dataFilter(startT, 'yyyyMMdd'));
        vm.endT = dataFilter((Date.parse(startT)) + 60 * 60 * 24 * 1000, 'yyyy/MM/dd');
        // 得到带格式且加上一个月
        var initDate = Date.parse(startTime);
        var time_end = new Date(initDate + 31 * 60 * 60 * 24 * 1000);
        vm.time_end = dataFilter(time_end, 'yyyy/MM');
        ChargeService.getDailyMonth(shopid, vm.time_start + "/01", vm.time_end + "/01").$promise.then(function (data) {
            if (vm.settleDate == judgedate) { // 查询本月流水时
                ChargeService.getCash(shopid, vm.startT, vm.endT, 1).$promise.then(function (intraday) { // 查询今日流水
                    // console.log(intraday);
                    if (intraday.length > 0) { // 今日有流水，将数据分装成与data相同类型数据，并加入data数据中
                        tradeTotalFee=0;
                        total(intraday, 0, intradaydate);
                        vm.intradayinfo = {
                            cashmains: intraday,
                            dailyReportTotal: TotalFee,
                        };
                        data.push(vm.intradayinfo);
                        // console.log(vm.settleDate);
                        ChargeService.getMonthly(vm.settleDate, shopid).$promise.then(function (monthly) { //
                            if (vm.settleDate == judgedate) {
                                monthly.tradeTotalFee += vm.intradayinfo.dailyReportTotal.tradeTotalFee;
                                monthly.tradeNum += vm.intradayinfo.dailyReportTotal.tradeNum;
                            }
                            vm.monthly = monthly;
                            console.log(vm.monthly)
                            vm.profit = true;
                        }, function (error) { // 当月报表不存在，今日流水存在时，直接将今日流水封装成月报表
                            if (error.data.status == 403) {
                                vm.profit = true;
                                vm.monthly = TotalFee;
                                console.log(vm.monthly)
                            }
                        });
                    }
                }, function (error) { // 查询本月但今日流水不存在时，查询本月日报表
                    ChargeService.getMonthly(vm.settleDate, shopid).$promise.then(function (monthly) {
                        console.log(monthly);
                        vm.monthly = monthly;
                        console.log(vm.monthly)
                        vm.profit = true;
                    });
                })
            } else { // 除查询当月外的其他月份
                ChargeService.getMonthly(vm.settleDate, shopid).$promise.then(function (monthly) {
                    console.log(monthly);
                    vm.monthly = monthly;
                    console.log(vm.monthly)
                    vm.profit = true;
                });
            }
            console.log(data)
            vm.dailymonth = data;
        });
    }
    function getMeal(modelid, callback) {
        ChargeService.getMeal(modelid,function (meal) {
            callback(meal);
        })
    }
    function total(arr, i, time) {
        if (i >= arr.length) {
            TotalFee.settleDate = time;
            TotalFee.shopid = shopid;
            TotalFee.tradeNum = arr.length;
            return TotalFee;
        }
        TotalFee.tradeTotalFee += arr[i].tradeTotalFee;
        total(arr, i + 1, time);
    }

    //初始化时间对象$scope.date，初始化全局只执行一次
    function initialization_date() {
        vm.date = {
            year: new Date().getFullYear(),
            get_month: function () {
                var month = new Date().getMonth() + 1;
                if (month < 10) {
                    return "0" + month;
                } else {
                    return "" + month
                }
            },
            get_day: function () {
                var day = new Date().getDate();
                if (day < 10) {
                    return "0" + day;
                } else {
                    return "" + day
                }
            }
        };
        vm.date.month = vm.date.get_month();
        vm.date.day = vm.date.get_day();
    }

    var arr = [];
    function initCount(data,allData) {
        // console.log(data,allData)
        var flag = {}; // 定义空对象，实现与数组交互
        var checkArr = prepareArr(arr, data); // 数组数据与传入数据对比，如果data在数组内，返回位置，否则false
        if (checkArr === false) {
            flag.id = data.modelid;
            getMeal(data.modelid, function (meal) {
                flag.name = meal.title;
                flag.value = data.tradeTotalFee;
                pieChart(arr);
            });
            arr.push(flag);
        } else {
            arr[checkArr].value += data.tradeTotalFee;
            pieChart(arr);
        }
    }

    function prepareArr(arr, data) {
        var r = arr.length;
        while (r--) {
            if (arr[r].id == data.modelid) {
                return r;
            }
        }
        return false;
    }

    // 时间选框控件
    $('#date').datetimepicker({
        format: "yyyy/MM/dd",
        startView: 3,
        minView: 3,
        autoclose: true,
        todayBtn: true,
        todayHighlight: true,
        initialDate: new Date(),
        endDate: $filter('date')(new Date(), 'yyyy/MM/dd')
    }).on('changeDate', function (date) {
        arr.length = 0;//初始化数组长度
        active(date.date);
        set_date_object(date);
    });

    // 构造时间对象$scope.date！！！依赖时间控件.on(){}的中间数据，仅在时间控件on(){}函数起效
    function set_date_object(date) {
        vm.date = {
            year: date.date.getFullYear(),
            get_month: function () {
                var month = date.date.getMonth() + 1;
                if (month < 10) {
                    return "0" + month;
                } else {
                    return "" + month
                }
            },
            get_day: function () {
                var day = date.date.getDate();
                if (day < 10) {
                    return "0" + day;
                } else {
                    return "" + day
                }
            }
        };
        vm.date.month = vm.date.get_month();
        vm.date.day = vm.date.get_day();
        $scope.$apply(vm.date);
    }

    $scope.$on('$destroy', function () {
        $("div.datetimepicker").remove()
    });

    //  饼图
    function pieChart(data) {
        // console.log(data)
        option = {
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)",
            },
            legend: {
                orient: 'vertical',
                left: 'left',
            },
            itemGap: 10,
            series: [
                {
                    type: 'pie',
                    radius: ['0', '40%'],
                    center: ['50%', '50%'],
                    data: data,
                    color: ['rgb(242,234,95)', 'rgb(239,177,96)', 'rgb(233,123,124)', '#F7E7A4', 'wheat'],
                    avoidLabelOverlap: true,
                    hoverAnimation: false,
                    silent: false,
                    label: {
                        normal: {
                            show: true,
                            position: 'left',
                            fontSize: '10',
                            textStyle: {
                                fontSize: 14,
                                color: 'black'
                            },
                            formatter: "{b}({d}%)",
                        },
                    },
                }
            ]

        };
        myChart.setOption(option);
    }

    // 时间过滤操作
    function dataFilter(timestamp, format){
        return $filter('date')(timestamp, format);
    }
}